<template>
  <el-container class="layout-container-demo" style="height: 500px">
    <el-aside width="250px">
      <el-scrollbar style="background-color: #AAB7BF">
        <el-menu style="background-color: #717980"
                 :default-openeds="['tags']"
                 @select="handleMenuSelect"
        >
          <el-sub-menu index="tags">
            <template #title>
              <el-icon><PriceTag /></el-icon>
              <span>文章标签 ({{ Object.keys(tagGroups).length }})</span>
            </template>
            <!-- 添加文章的按钮 -->
            <div class="add-tag-container">
              <el-button
                  type="text"
                  :icon="Plus"
                  @click.stop="openAddArticleDialog"
                  class="add-tag-btn"
              >
                添加文章
              </el-button>
            </div>
            <div v-for="(articles, tagName) in tagGroups" :key="tagName" class="tag-item">
              <el-sub-menu :index="'tag-' + tagName">
                <template #title>
                  <span>{{ tagName }} ({{ articles.length }})</span>
                </template>
                <el-menu-item
                    v-for="(article, index) in articles"
                    :key="index"
                    :index="'tag-' + tagName + '-article-' + article.id"
                >
                  {{ article.title }}
                </el-menu-item>
              </el-sub-menu>
            </div>
          </el-sub-menu>
        </el-menu>
      </el-scrollbar>
    </el-aside>

    <el-main>
      <div v-if="selectedArticle" class="article-container">
        <h2>{{ selectedArticle.title }}</h2>
        <p class="meta">
          <el-tag size="small">{{ selectedArticle.tag }}</el-tag>
          <span style="margin-left: 10px;">{{ selectedArticle.date }}</span>
        </p>
        <div class="content">{{ selectedArticle.content }}</div>
      </div>
      <div v-else class="empty-state">
        <el-icon><Document /></el-icon>
        <p>请从左侧选择一篇文章</p>
      </div>
    </el-main>
  </el-container>

  <!-- 添加文章弹窗 -->
  <el-dialog
      v-model="articleDialogVisible"
      title="添加新文章"
      width="70%"
  >
    <el-form :model="articleForm" label-width="80px">
      <el-form-item label="文章标题">
        <el-input v-model="articleForm.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="文章标签">
        <el-select
            v-model="articleForm.tag"
            filterable
            allow-create
            default-first-option
            placeholder="选择或创建标签"
        >
          <el-option
              v-for="tag in existingTags"
              :key="tag"
              :label="tag"
              :value="tag"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布日期">
        <el-date-picker
            v-model="articleForm.date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="文章内容">
        <el-input
            v-model="articleForm.content"
            type="textarea"
            :rows="5"
            placeholder="请输入文章内容"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="articleDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveArticle">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { PriceTag, Plus, Document } from '@element-plus/icons-vue'

// 文章列表（双向绑定）
const articleList = ref([
  { id: 1, title: 'Vue 3 新特性', date: '2023-01-15', tag: 'Vue', content: 'Vue 3 引入了组合式API、性能优化等新特性...' },
  { id: 2, title: 'Pinia 状态管理', date: '2023-02-20', tag: 'Vue', content: 'Pinia 是 Vue 的轻量级状态管理库...' },
  { id: 3, title: 'React Hooks 指南', date: '2023-03-10', tag: 'React', content: 'Hooks 让函数组件拥有状态和生命周期...' },
  { id: 4, title: 'Redux 原理分析', date: '2023-04-05', tag: 'React', content: 'Redux 的核心原理和工作流程...' },
  { id: 5, title: 'ES6 新特性', date: '2023-01-05', tag: 'JavaScript', content: '箭头函数、解构赋值、模板字符串等...' },
  { id: 6, title: 'Promise 详解', date: '2023-02-15', tag: 'JavaScript', content: 'Promise 的用法和原理分析...' }
])

// 计算属性：按标签分组文章
const tagGroups = computed(() => {
  const groups = {}
  articleList.value.forEach(article => {
    if (!groups[article.tag]) {
      groups[article.tag] = []
    }
    groups[article.tag].push(article)
  })
  return groups
})

// 计算属性：现有标签列表
const existingTags = computed(() => {
  return Object.keys(tagGroups.value)
})

const selectedArticle = ref(null)

// 文章对话框相关
const articleDialogVisible = ref(false)
const articleForm = ref({
  title: '',
  tag: '',
  date: new Date().toISOString().split('T')[0],
  content: ''
})

// 打开添加文章对话框
const openAddArticleDialog = () => {
  articleForm.value = {
    title: '',
    tag: '',
    date: new Date().toISOString().split('T')[0],
    content: ''
  }
  articleDialogVisible.value = true
}

// 保存文章
const saveArticle = () => {
  if (!articleForm.value.title.trim()) {
    ElMessage.error('文章标题不能为空')
    return
  }

  if (!articleForm.value.tag.trim()) {
    ElMessage.error('文章标签不能为空')
    return
  }

  const newArticle = {
    id: Date.now(), // 使用时间戳作为ID
    title: articleForm.value.title,
    date: articleForm.value.date,
    tag: articleForm.value.tag,
    content: articleForm.value.content
  }

  articleList.value.push(newArticle)
  ElMessage.success('文章添加成功')
  articleDialogVisible.value = false
}

// 处理菜单选择
const handleMenuSelect = (index) => {
  const parts = index.split('-')
  if (parts.length === 4 && parts[0] === 'tag' && parts[2] === 'article') {
    const tagName = parts[1]
    const articleId = parseInt(parts[3])
    selectedArticle.value = articleList.value.find(article =>
        article.tag === tagName && article.id === articleId
    )
  }
}
</script>

<style scoped>
.layout-container-demo {
  --aside-bg-color: #1f2d3d;
  --menu-bg-color: #324157;
  --menu-hover-color: #475669;
  --menu-active-color: #20a0ff;
  --text-color: #000000;
  --text-secondary: #232222;
  --primary-color: #20a0ff;
  --danger-color: #ff4949;
}

.layout-container-demo .el-aside {
  background-color: var(--aside-bg-color);
  color: var(--text-color);
}

.layout-container-demo .el-menu {
  background-color: var(--menu-bg-color);
  border-right: none;
}

.layout-container-demo .el-menu-item,
.layout-container-demo .el-sub-menu__title {
  color: var(--text-color);
}

.layout-container-demo .el-menu-item:hover,
.layout-container-demo .el-sub-menu__title:hover {
  background-color: var(--menu-hover-color);
}

.layout-container-demo .el-menu-item.is-active {
  color: var(--primary-color);
  background-color: var(--menu-hover-color);
}

.add-tag-container {
  padding: 8px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.add-tag-btn {
  width: 100%;
  color: var(--text-secondary);
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding-left: 10px;
}

.add-tag-btn:hover {
  color: var(--primary-color);
  background-color: var(--menu-hover-color);
}

.tag-item {
  position: relative;
}

.layout-container-demo .el-main {
  padding: 20px;
  background-color: #f5f7fa;
}

.article-container {
  max-width: 800px;
  margin: 0 auto;
  color: black;
}

.article-container h2 {
  color: black;
  margin-bottom: 10px;
}

.article-container .meta {
  color: black;
  font-size: 14px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.empty-state {
  color: black;
}

.el-scrollbar__thumb {
  background-color: rgba(255, 255, 255, 0.2) !important;
}

.el-scrollbar__thumb:hover {
  background-color: rgba(255, 255, 255, 0.3) !important;
}
</style>